package gui;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileWriter;

import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import localhost._8080.metaimage.Client;

public class SplitPaneDemo implements ListSelectionListener,MouseListener {
    private static JLabel picture;
    private static JList list;
    private JSplitPane splitPane;
    private static String[] imageNames = { "" };
    
    private JButton getXml;
    private JButton getPng;
    
      
    public SplitPaneDemo() {

    	
        //Mettre à jour la liste des images
    	try {
	    	imageNames = new String[Client.p.getMyImagesName(Client.id).toArray(imageNames).length];
	    	Client.p.getMyImagesName(Client.id).toArray(imageNames);
    	}
    	catch(Exception e){
    		
    	}
    	
    	Container listCont = new Container();
    	listCont.setLayout(new BoxLayout(listCont, BoxLayout.Y_AXIS));
	    	// Liste de fichier XML
	        list = new JList(imageNames);
	        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	        list.setSelectedIndex(0);
	        list.addListSelectionListener(this);      
	        JScrollPane listScrollPane = new JScrollPane(list);
	        
	        //Bouton pour avoir XML et png
	        getXml = new JButton("Get Xml file");
	        getXml.setAlignmentX(Component.CENTER_ALIGNMENT);
	        getXml.addMouseListener(this);
	        getPng = new JButton("Get Png file");
	        getPng.setAlignmentX(Component.CENTER_ALIGNMENT);
	        getPng.addMouseListener(this);
	        
	        
	        listCont.add(listScrollPane);
	        listCont.add(getXml);
	        listCont.add(getPng);
	        
        
        // Appercu des images
        picture = new JLabel();
        picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
        picture.setHorizontalAlignment(JLabel.CENTER);
        JScrollPane pictureScrollPane = new JScrollPane(picture);

        //Create a split pane with the two scroll panes in it.
        this.splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                   listCont, pictureScrollPane);
        this.splitPane.setOneTouchExpandable(true);
        this.splitPane.setDividerLocation(200);

        //Provide minimum sizes for the two components in the split pane.
        listScrollPane.setMinimumSize(new Dimension(200,200));
        pictureScrollPane.setMinimumSize(new Dimension(200,200));

        //Provide a preferred size for the split pane.
        this.splitPane.setPreferredSize(new Dimension(500, 500));
        updateLabel(imageNames[list.getSelectedIndex()]);
        
    }
    
    //Listens to the list
    public void valueChanged(ListSelectionEvent e) {
        JList list = (JList)e.getSource();        
        updateLabel(imageNames[list.getSelectedIndex()]);
    }
    
    //Update list
    public static void updateList(){
    	try {
    		list.setVisible(false);
        	imageNames = new String[Client.p.getMyImagesName(Client.id).toArray(imageNames).length];
        	Client.p.getMyImagesName(Client.id).toArray(imageNames);        	
        	list.setListData(imageNames);
        	}
        	catch(Exception e){
        		
        	}
        	finally{
        		list.setSelectedIndex(0);  	
            	list.setVisible(true);
        	}
    }
    
    
    //Renders the selected image
    public static void updateLabel (String name) {
    	if(name != null) {
    		
	    	try {
	    		BufferedImage buf;
	    		//buf = ImageIO.read(new ByteArrayInputStream(Client.p.getImagePng(Client.id,name.substring(0, name.length()-4))));
	    		buf = ImageIO.read(new ByteArrayInputStream(Client.p.getImagePng(Client.id,name.substring(0, name.length()-4))));
	    		ImageIcon icon = new ImageIcon(buf);			
		        picture.setIcon(icon);
		        if  (icon != null) {
		            picture.setText(null);
		        }
				
			} catch (Exception e) {
				e.printStackTrace();
			}

			
	    
    	}
    }

    //Used by SplitPaneDemo2
    public JList getImageList() {
        return list;
    }

    public JSplitPane getSplitPane() {
        return splitPane;
    }

	@Override
	public void mouseClicked(MouseEvent m) {
		if((JButton)m.getSource() == this.getPng ){
			try{
				Client.execute("getImagePng "+((String) list.getSelectedValue()).split(".xml")[0]);
				JOptionPane.showMessageDialog(picture,
					    "Image successfuly saved in the current directory", 
					    "Message", JOptionPane.INFORMATION_MESSAGE);
			}
			catch(Exception e){
				JOptionPane.showMessageDialog(picture,
					    "Fail to save the image in the current directory", 
					    "Error", JOptionPane.ERROR_MESSAGE);
				
			}
			
		}
		else if((JButton)m.getSource() == this.getXml ){
			try{
				String fileName = new String  (((String) list.getSelectedValue()).split(".xml")[0] );
				if(Client.p.isGrantedUser(Client.id, "getXML", fileName, null)) {
					String p = Client.p.getXML(Client.id,  fileName );
					FileWriter fw = new FileWriter(fileName+".xml");
					fw.write(p);
					fw.close();
				}
				JOptionPane.showMessageDialog(picture,
					    "Xml successfuly saved in the current directory", 
					    "Message", JOptionPane.INFORMATION_MESSAGE);
			}
			catch(Exception e){
				JOptionPane.showMessageDialog(picture,
					    "Fail to save xml in the current directory", 
					    "Error", JOptionPane.ERROR_MESSAGE);
				
			}
			
		}
		
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		
		
	}

   
    /** Returns an ImageIcon, or null if the path was invalid. */
    /*protected static ImageIcon createImageIcon(String path) {
    	//java.net.URL imgURL = SplitPaneDemo.class.getResource(path);
    	java.net.URL imgURL = null;
		try {
			imgURL = new java.net.URL(path);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
    	if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }*/

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
   /* private static void createAndShowGUI() {

        //Create and set up the window.
        JFrame frame = new JFrame("SplitPaneDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
        frame.getContentPane().add(splitPaneDemo.getSplitPane());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }*/
}